package com.klikmee.sms.core.base.communicator.telenor;

import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.dao.ConfigDAO;
import com.klikmee.sms.core.base.dao.ConfigFacadeLocal;
import com.klikmee.sms.core.base.util.Constants;
import com.klikmee.sms.core.ws.telenor.client.delrep.DeliveryStatusType;
import com.klikmee.sms.core.ws.telenor.client.delrep.GetSmsDeliveryStatusByCpseq;
import com.klikmee.sms.core.ws.telenor.client.delrep.GetSmsDeliveryStatusByCpseqResponse;
import com.klikmee.sms.core.ws.telenor.client.delrep.GetSmsDeliveryStatusCP;
import com.klikmee.sms.core.ws.telenor.client.delrep.GetSmsDeliveryStatusCPResponse;
import com.klikmee.sms.core.ws.telenor.client.delrep.Potpis;
import com.klikmee.sms.core.ws.telenor.client.delrep.SmsParlayx;

public class GetDeliveryReportsFromCPA {

    public static Logger logger = Logger.getLogger( GetDeliveryReportsFromCPA.class );
    private SmsParlayx deliveryEndpoint = null;
    private URL wsdlURL;
    private String overrideEndpointAddress;
    private TelenorCommunicatorImpl communicator = null;
    private ConfigDAO configDAO;
    private String cpId = null;
    private Potpis credentials = null;

    public GetDeliveryReportsFromCPA() {
    }

    public void init() {
        
        deliveryEndpoint = new com.klikmee.sms.core.ws.telenor.client.delrep.SmsParlayxService(wsdlURL, new QName("http://telenor.cpa.parlayx.sms", "SmsParlayxService")).getSmsParlayxPort();
        // if this address is set override endpoint
        if(overrideEndpointAddress != null){
            BindingProvider sendsmsBP = (BindingProvider) deliveryEndpoint;
            Map<String, Object> sendsmsRequestContext = sendsmsBP.getRequestContext();
            sendsmsRequestContext.put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, overrideEndpointAddress );
        }
    }

    public void checkForReports() {


        // this will be delivered to telenor communicator
        List<DeliveryStatusType> deliveryReports = null;

        String cpseqIdFailed = configDAO.getParameterValue( Constants.CONF_TELENOR_DELIVERY_REQUEST_CPSEQ_VALUE );

        // if there is no previous failed request
        if (cpseqIdFailed == null) {
            // generate cpseq id
            long currentCpseqid = System.currentTimeMillis();

            // create web service parameters
            GetSmsDeliveryStatusCP parameters = new GetSmsDeliveryStatusCP();
            parameters.setCpseqid( currentCpseqid );
            parameters.setRegistrationIdentifier( Long.parseLong( cpId ) );

            // before trying to get delivery reports, save cpseqid so it can be
            // used later if operation failes
            configDAO.createParameter(
                    Constants.CONF_TELENOR_DELIVERY_REQUEST_CPSEQ_VALUE,
                    String.valueOf( currentCpseqid ) );

            try {
                GetSmsDeliveryStatusCPResponse result = deliveryEndpoint.getSmsDeliveryStatusCP(
                        parameters,
                        credentials );

                deliveryReports = result.getReturn();

                // if everything went ok, delete cpseq for database
                configDAO.deleteParameter( Constants.CONF_TELENOR_DELIVERY_REQUEST_CPSEQ_VALUE );
            } catch (Exception e) {

                logger.fatal( "Error getting delivery reports using getSmsDeliveryStatusCP() method", e );
            }

        } // if there is previous request which failed, try to execute it again
        else {

            long cpseqFailedLong = Long.parseLong( cpseqIdFailed );

            try {

                GetSmsDeliveryStatusByCpseq parameters = new GetSmsDeliveryStatusByCpseq();
                parameters.setCpseqid( cpseqFailedLong );
                parameters.setRegistrationIdentifier( Long.parseLong( cpId ) );

                GetSmsDeliveryStatusByCpseqResponse result = deliveryEndpoint.getSmsDeliveryStatusByCpseq(
                        parameters,
                        credentials );

                deliveryReports = result.getReturn();

                // if everything ok, delete cpseqid from db
                configDAO.deleteParameter( Constants.CONF_TELENOR_DELIVERY_REQUEST_CPSEQ_VALUE );
            } catch (Exception e) {
                logger.fatal( "Error getting delivery reports using getSmsDeliveryStatusByCpseq() method", e );
            }

        }

        if (deliveryReports != null) {
            communicator.onDeliveryReports( deliveryReports );
//			LOGGER.info("chechForReports() invoked, fetched "
//					+ deliveryReports.size() + " reports");
        }

    }

    public void setCommunicator( TelenorCommunicatorImpl communicator ) {
        this.communicator = communicator;
    }

    public void setConfigDAO( ConfigDAO configDAO ) {
        this.configDAO = configDAO;
    }

    public void setCpId( String cpId ) {
        this.cpId = cpId;
    }

    public void setCredentials( Potpis credentials ) {
        this.credentials = credentials;
    }

    public void setOverrideEndpointAddress( String overrideEndpointAddress ) {
        this.overrideEndpointAddress = overrideEndpointAddress;
    }

    public void setWsdlURL( URL wsdlURL ) {
        this.wsdlURL = wsdlURL;
    }

    

}
